package io.gitee.heis.vehicle.race.sample03;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;

@Component
public class Race03 {

    /**
     * 车开过的痕迹字符
     */
    private final static char DONE_SYMBOL='_';
    /**
     * 赛道长度
     */
    private int barLen=80;

    /**
     * 用于赛道显示的字符
     */
    private String showChar="\uD83D\uDE97";

    /**
     * 车
     */
    @Autowired
    private Vehicle vehicle;

    public Race03() {
    }

    /**
     * 显示赛道
     */
    public void show(long value,long startTime) {
        if (value < 0 || value > 100) {
            return;
        }
        reset();
        // 比例
        float rate = (float) (value*1.0 / 100);
        // 比例*赛道总长度=当前长度
        draw(barLen, rate,startTime);
        if (value == 100L) {
            afterComplete();
        }
    }

    /**
     * 绘制汽车竞赛
     * @param barLen 赛道长度
     * @param rate 完成赛道百分比
     * @param startTime 开始时间
     */
    private void draw(int barLen, float rate,long startTime) {
        int len = (int) (rate * barLen);
        System.out.print(vehicle.getEngine().getName()+"|");
        for (int i = 0; i < barLen-len; i++) {
            System.out.print(" ");
        }
        System.out.print(showChar);
        for (int i = 0; i < len; i++) {
            System.out.print(DONE_SYMBOL);
        }
        double timeCost=(System.currentTimeMillis()-startTime)/1000d;
        System.out.print(" |" + format(rate)+", "+timeCost+"秒");
    }

    /**
     * 光标移动到行首
     */
    private void reset() {
        System.out.print('\r');
    }

    /**
     * 完成后换行
     */
    private void afterComplete() {
        System.out.print('\n');
    }

    private String format(float num) {
        return new DecimalFormat("#.##%").format(num);
    }

    public void start() throws InterruptedException {
        long startTime=System.currentTimeMillis();
        for (int i = 1; i <= 100; i++) {
            show(i,startTime);
            Thread.sleep(10000/vehicle.getPower());
        }
    }

    public void setVehicle(Vehicle vehicle) {
        this.vehicle = vehicle;
    }
}